const { Model, Schema } = require('../helps/model');
const { formatData } = require('../helps/tools');
// const { executor } = require('../helps/model');
// CREATE TABLE `user_message` (
//   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//   `robot_id` int(11) unsigned NOT NULL COMMENT '机器人id',
//   `title` varchar(255) NOT NULL DEFAULT "" COMMENT '消息标题',
//   `content` text COMMENT '更新内容',
//   `module` varchar(255) NOT NULL COMMENT '模块',
//   `module_id` int(11) NOT NULL COMMENT '模块id',
//   `is_read` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT '状态：1已读，0未读',
//   `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
//   `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
//   `delete_time` datetime,
//   PRIMARY KEY (`id`),
//   KEY `robot_read` (`robot_id`, `is_read`) USING BTREE
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户消息表';

const schema = new Schema({
  primary: 'id',
  create_time: true,
  update_time: true,
  soft_delete: true,
  auto_increment: true,
  fields: ['id', 'robot_id', 'title', 'content', 'module', 'module_id', 'is_read'],
  default: {
    title: '',
    is_read: 0,
  },
});

export const model = new Model('user_message', schema);

/**
 * 查找
 * @param id
 * @returns {*}
 */
export function get(id) {
  return model.findByKey(id);
}

/**
 * 查找列表
 * @param ids
 * @returns {*}
 */
export function getIds(ids) {
  return model.findByQuery({
    where: [
      ['id', 'in', ids],
    ],
  });
}

/**
 * 创建
 * @param data
 * @returns {*}
 */
export function add(data) {
  return model.insert(formatData(schema.baseFields(), data));
}

/**
 * 更新
 * @param id
 * @param data
 * @returns {*}
 */
export function put(id, data) {
  return model.updateByKey(id, formatData(schema.baseFields(), data));
}

/**
 * 删除
 * @param id
 * @returns {*}
 */
export function del(id) {
  return model.deleteByKey(id);
}

/**
 * 列表分页
 * @param page
 * @param number
 * @returns {*}
 */
export function search(where, page = 1, number = 50, order = 'id', direction = 'desc') {
  return model.findListAndCount(where, page, number, `\`${order}\` ${direction}`);
}

export function list(page, number, order, direction) {
  return search([], page, number, order, direction);
}

export function listByUnread(robot_id, page, number) {
  let where = [
    ['robot_id', '=', robot_id],
    ['is_read', '=', 0],
  ];
  return search(where, page, number)
    .then((result) => {
      if (result.count > 0) {
        return model.updateByQuery({
          where: [
            ['robot_id', '=', robot_id],
            ['is_read', '=', 0],
          ],
        }, {
          is_read: 1,
        }).then(() => {
          return result;
        });
      } else {
        return result;
      }
    });
}
